package net.sureon.biz;

import net.sureon.common.SureonConstants;
import net.sureon.common.security.Role;
import net.sureon.common.security.SecurityUtils;
import net.sureon.dao.User;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * the user BIZ object.
 * 
 * @author jason
 */
public class UserBO extends DefaultCategory implements CategoryAble {
	private User userVO;
	private static final Log logger = LogFactory.getLog(UserBO.class);

	public UserBO(User userVO) {
		this.userVO = userVO;
	}

	/**
	 * @return the userVO
	 */
	public User getUserVO() {
		return userVO;
	}

	public long getCompanyID() {
		return getUserVO().getCompanyID();
	}

	public long getGroupID() {
		return getUserVO().getGroupID();
	}

	public long getUserID() {
		return getUserVO().getUserID();
	}

	public Role getRole() {
		return Role.getRole(getUserVO().getRole());
	}

	public boolean verifyPassword(String inputPassword) {
		if (logger.isDebugEnabled()) {
			logger.debug("user found, userID=" + getUserID());
		}
		String incrypetPass = generateEncryptPassword(inputPassword);
		String dbPassword = getUserVO().getPassword();
		if (dbPassword != null) {
			return dbPassword.equals(incrypetPass);
		} else {
			logger.error("error ... password got from database is null");
		}
		return false;
	}

	public boolean verifyToken(String token) {
		return SecurityUtils.verifyMessageDigest(getUserVO().getSalt(), token,
				generateTokenMessage());
	}

	public String generateUserToken() {
		return SecurityUtils.makeMessageDigest(getUserVO().getSalt(),
				generateTokenMessage());
	}

	private String generateEncryptPassword(String inputPassword) {
		return SecurityUtils.generateSHA512Hash(getUserVO().getSalt() + ":"
				+ inputPassword);
	}

	private String generateTokenMessage() {
		return getCompanyID() + "~" + getUserID() + "~"
				+ getUserVO().getUserName();
	}

	public void activateUser() {
		getUserVO().setStatus(SureonConstants.USER_STATUS_ACTIVE);
	}

	public void deactivateUser() {
		getUserVO().setStatus(SureonConstants.USER_STATUS_INACTIVE);
	}

	public boolean isActive() {
		return SureonConstants.USER_STATUS_ACTIVE.equals(getUserVO()
				.getStatus());
	}
}
